import React, { useState, useEffect } from "react";
import { Card, Table, message, Spin } from "antd";
import { PieChart, Pie, Cell, Tooltip, Legend, ResponsiveContainer } from "recharts";
import axios from "axios";
import "./TradeHoldings.scss";

const COLORS = ["#0088FE", "#00C49F", "#FFBB28", "#FF8042", "#A28CFF"];

const TradeHoldings = () => {
  const [holdings, setHoldings] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchHoldings = async () => {
      try {
        const token = localStorage.getItem("jwt_token");
        if (!token) {
          message.error("用户未登录，请登录后重试");
          return;
        }

        const response = await axios.get("/api/product/list", {
          headers: { Authorization: `Bearer ${token}` },
        });

        if (response.data.code === 0) {
          
          // 获取历史交易记录
          const rawData = response.data.data;

          // 根据股票代码合并记录，计算总持仓数量和持仓价值
          const aggregatedData = rawData.reduce((acc, item) => {
            const existing = acc[item.code];
            const latestPrice = item.latest_price / 100; // 单位转换

            if (existing) {
              // 更新现有记录
              existing.quantity += item.quantity;

              // 总投资金额是一个累加值，是按各自买入时候的最新价来算的
              existing.totalValue += item.quantity * latestPrice;
            } else {
              // 添加新记录
              if(item.type==="fund"){
                item.type = "基金";
              }
              acc[item.code] = {
                name: item.name,
                type: item.type,
                latest_price: latestPrice.toFixed(2),
                quantity: item.quantity,
                totalValue: item.quantity * latestPrice,
              };
            }

            return acc;
          }, {});

          // 转换为数组格式并计算比例
          const dataArray = Object.values(aggregatedData);
          const totalPortfolioValue = dataArray.reduce((sum, item) => sum + item.totalValue, 0);

          const finalHoldings = dataArray.map((item) => ({
            ...item,
            percentage: (item.totalValue / totalPortfolioValue) * 100,
          }));

          setHoldings(finalHoldings);
        } else {
          message.error(`获取持仓数据失败: ${response.data.message}`);
        }
      } catch (error) {
        message.error("请求持仓数据失败，请检查网络或联系管理员");
      } finally {
        setLoading(false);
      }
    };

    fetchHoldings();
  }, []);

  // 转换数据为 PieChart 的格式
  const chartData = holdings.map((item) => ({
    name: item.name,
    value: parseFloat(item.percentage.toFixed(2)),
  }));

  const columns = [
    { title: "股票名称", dataIndex: "name", key: "name" },
    { title: "类型", dataIndex: "type", key: "type" },
    { title: "持仓数量", dataIndex: "quantity", key: "quantity" },
    { title: "最新价格", dataIndex: "latest_price", key: "latest_price" },
    { title: "持仓比例 (%)", dataIndex: "percentage", key: "percentage", render: (text) => `${text.toFixed(2)}%` },
  ];

  return (
    <div className="product-manage-container">
      <Spin spinning={loading}>
        <Card title="用户持仓概览" className="chart-card">
          {holdings.length > 0 ? (
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={chartData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="50%"
                  outerRadius={100}
                  label
                >
                  {chartData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          ) : (
            <div className="loading">暂无持仓数据</div>
          )}
        </Card>

        <Card title="详细持仓信息" className="table-card">
          <Table
            columns={columns}
            dataSource={holdings}
            rowKey={(record) => record.name}
            pagination={{ pageSize: 5 }}
          />
        </Card>
      </Spin>
    </div>
  );
};

export default TradeHoldings;
